package com.sky.product.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.api.domain.entity.Dish;
import com.sky.common.constant.MessageConstant;
import com.sky.common.constant.StatusConstant;
import com.sky.common.exception.DeletionNotAllowedException;
import com.sky.common.result.PageResult;

import com.sky.product.domain.dto.DishDTO;
import com.sky.product.domain.dto.DishPageQueryDTO;
import com.sky.api.domain.entity.DishFlavor;
import com.sky.api.domain.entity.Setmeal;
import com.sky.api.domain.vo.DishVO;
import com.sky.product.mapper.DishFlavorMapper;
import com.sky.product.mapper.DishMapper;
import com.sky.product.mapper.SetmealDishMapper;
import com.sky.product.mapper.SetmealMapper;
import com.sky.product.service.DishService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {

    private final DishMapper dishMapper;
    private final DishFlavorMapper dishFlavorMapper;
    private final SetmealDishMapper setmealDishMapper;
    private final SetmealMapper setmealMapper;
//    private final RedisTemplate redisTemplate; 改用springCaching注解

    /**
     * 新增菜品和对应口味信息
     *
     * @param dishDTO 新增菜品和对应口味信息
     */
    @Transactional  // 涉及多张表的操作,需要保证原子性,所以开启事务
    public void saveWithFlavor(DishDTO dishDTO) {

        final Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);

        // 向菜品表中插入一个菜品
        dishMapper.insert(dish);

        // 获取insert语句生成的主键值
        final Long dishId = dish.getId();

        // 向口味表中插入n个口味
        final List<DishFlavor> flavors = dishDTO.getFlavors();
        if (null != flavors && flavors.size() > 0) {
            // 插入前循环设置口味的菜品id
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            // 批量插入口味
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 分页查询菜品列表
     *
     * @param dishPageQueryDTO 分页查询条件
     * @return PageResult
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        // 参数: 当前页, 每页条数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        final Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids 菜品id列表
     */
    public void deleteBatch(List<Long> ids) {
        // 1. 判断当前菜品能否被删除
        // -- 是否存在起售中的菜品
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // -- 是否存在关联的套餐
        final List<Long> setMealIds = setmealDishMapper.getSetmealIdByDishIds(ids);
        if (null != setMealIds && setMealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 2. 删除菜品
        // 优化前,循环执行sql删除
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
        // 3. 不管是否存在,都删除菜品关联的口味
//            dishFlavorMapper.deleteByDishId(id);
//        }
        // 优化后: 批量删除菜品和口味, 一次性删除
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品和对应口味信息
     *
     * @param id 菜品id
     */
    public DishVO getByIdWithFlavor(Long id) {
        // 1. 根据id查询菜品
        final Dish dish = dishMapper.getById(id);
        // 2. 根据id查询菜品对应的口味
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        // 3. 封装成VO返回
        final DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /**
     * 根据id更新菜品和对应口味信息
     *
     * @param dishDTO 菜品信息
     */
    public void updateWithFlavor(DishDTO dishDTO) {
        // 1.修改菜品表的基本信息,其他字段不变,故传递的是Dish对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        // 2.删除原有的口味
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        // 3.重新插入新的口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            // 若有值,则设置口味的菜品id,并插入口味表
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDTO.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据id更新菜品状态
     *
     * @param status 状态
     * @param id     菜品id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        final Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        // 若停售,则关联的套餐菜品也停售
        if (dish.getStatus() == StatusConstant.DISABLE) {
            final List<Long> dishIds = new ArrayList<>();
            dishIds.add(dish.getId());
            final List<Long> setmealIds = setmealDishMapper.getSetmealIdByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId 分类id
     * @return List<Dish> 菜品列表
     */
    public List<Dish> list(Long categoryId) {
        final Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品及其对应口味信息
     *
     * @param dish 菜品信息
     * @return List<DishVO> 菜品及其对应口味信息
     */
    @Cacheable(cacheNames = "dishCache", key = "#dish.categoryId")
    public List<DishVO> listWishFlavor(Dish dish) {
        // 先查询数据是否存在于缓存中
//        final String key = "dish_" + dish.getCategoryId();  // 构造redis中的key,规则: dish_分类id
        // 从缓存中获取数据
//        ArrayList<DishVO> dishVOList =(ArrayList<DishVO>) redisTemplate.opsForValue().get(key);
//        if (dishVOList != null && dishVOList.size() > 0){
//            return dishVOList;   // 缓存命中,直接返回
//        }

        // 缓存未命中,查询数据库,并缓存到redis中

        // 查询菜品信息
        final List<Dish> dishList = dishMapper.list(dish);
        // 循环查询每个菜品的口味信息
        ArrayList<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            final DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            final List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);

            dishVOList.add(dishVO);
        }

        // 缓存到redis
//        redisTemplate.opsForValue().set(key, dishVOList);
        return dishVOList;
    }

    @Override
    public Integer countByMap(HashMap<Object, Object> map) {
        return dishMapper.countByMap(map);
    }

}
